package com.example.cardgame

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.model.CardMatchingGame

var game: CardMatchingGame = CardMatchingGame(24)

class ThirdActivity : AppCompatActivity() {
    lateinit var adapter: CardAdapter

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)

        val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
        adapter = CardAdapter(game)
        recyclerView.adapter = adapter

        val config = resources.configuration
        recyclerView.layoutManager = if (config.orientation == Configuration.ORIENTATION_PORTRAIT)
            GridLayoutManager(this, 4)
        else
            GridLayoutManager(this, 6)

        // 卡片点击事件
        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()
        }

        // 分数 + 模式显示初始化
        updateUI()

        // 重置按钮
        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            game.reset()
            updateUI()
        }

        // ✅ 模式切换按钮
        val modeButton = findViewById<Button>(R.id.button_mode)
        val modeText = findViewById<TextView>(R.id.text_mode)

        modeButton.setOnClickListener {
            if (game.matchMode == 2) {
                game.matchMode = 3
                modeButton.text = "切换为两张模式"
                modeText.text = "当前模式：三张匹配"
                Toast.makeText(this, "已切换为三张匹配模式", Toast.LENGTH_SHORT).show()
            } else {
                game.matchMode = 2
                modeButton.text = "切换为三张模式"
                modeText.text = "当前模式：两张匹配"
                Toast.makeText(this, "已切换为两张匹配模式", Toast.LENGTH_SHORT).show()
            }
            game.reset()
            updateUI()
        }

        // 返回按钮
        val back = findViewById<Button>(R.id.button_back)
        back.setOnClickListener { finish() }
    }

    fun updateUI() {
        adapter.notifyDataSetChanged()
        val scoreTextView: TextView = findViewById(R.id.textView)
        scoreTextView.text = getString(R.string.score) + game.score.toString()
    }
}
